package com.boarsoft.boar.agent.nginx;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import com.boarsoft.config.core.ConfigFileListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.boarsoft.agent.AgentService;
import com.boarsoft.bean.ReplyInfo;

public class NginxConfListener implements ConfigFileListener {
	private static final Logger log = LoggerFactory.getLogger(NginxConfListener.class);

	/** 引用本地 agentService bean */
	@Autowired
	@Qualifier("agentService")
	protected AgentService agentX;

	/** nginx所在绝对路径 */
	protected String path;
	/** 更新nginx所需要执行的shell */
	protected String shell = "nginx/reload.sh";
	/** */
	protected int port = 80;
	/** */
	protected FileFilter fileFilter = new FileFilter() {
		@Override
		public boolean accept(File f) {
			return f.getName().equals("nginx.conf");
		}
	};

	@Override
	public boolean onRemove(String frp) {
		// Nothing to do
		return false;
	}

	@Override
	public boolean onReady(String code) {
		ReplyInfo<Object> ri;
		try {
			ri = agentX.executeCmd(shell, new String[] {});
			log.warn("Result of shell execution {} = {}", shell, ri.getData());
			return ri.isSuccess();
		} catch (IOException | InterruptedException e) {
			log.error("Error on execute shell {}", shell, e);
			return false;
		}
	}

	@Override
	public String getAbosoluteDir() {
		return path;
	}

	@Override
	public String getAbosultePath(String rp) {
		return path.concat(rp);
	}

	@Override
	public String getAbosultePath() {
		return path;
	}

	@Override
	public String getRelativeDir() {
		return "";
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getShell() {
		return shell;
	}

	public void setShell(String shell) {
		this.shell = shell;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public FileFilter getFileFilter() {
		return fileFilter;
	}

	public void setFileFilter(FileFilter fileFilter) {
		this.fileFilter = fileFilter;
	}
}